﻿<!--
 * @Author: 哈兰德
 * @Description: 轮播模板模块，由于当前选中模块需要关联其他组件，状态需保存在父组件钟
-->
<template>
  <div class="image-template">
    <div>选择模版：{{ selectedTemplate.name }}</div>
    <div class="template-list">
      <div
        v-for="item in templateList"
        :key="item.id"
        class="item"
        :class="{ 'item-on': selectedTemplate.id === item.id }"
        @click="selectTemplate(item, true)"
      >
        <img
          :title="item.name"
          style="width: 70%"
          :src="
            selectedTemplate.id === item.id ? item.icon_on : item.icon
          "
        />
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapMutations } from 'vuex'

export default {
  props: {
    selectedTemplate: {
      type: Object,
      default: () => ({})
    },
    templateList: {
      type: Array,
      default: () => []
    }
  },
  computed: {
    ...mapGetters('main', ['selectedComponent']),
  },
  mounted() {
    const layout = this.selectedComponent.layout
    let item
    if (layout) {
      item = this.templateList.find(per => per.id === layout)
    } else {
      item = this.templateList[0]
    }
    this.selectTemplate(item)
  },
  methods: {
    ...mapMutations('main', ['editComponent']),
    selectTemplate (item, flag) {
      this.updateComponentData('layout', item.id)
      if (flag) {
        if ([3, 4].includes(item.id)) {
          this.updateComponentData('imageGutter', 6)
        } else {
          this.updateComponentData('imageGutter', 0)
        }
        // 切换模板时要刷新
        this.updateComponentData('swipeVisible', false)
        setTimeout(() => {
          this.updateComponentData('swipeVisible', true)
        }, 50)
      }
      this.$emit('setCurrentTemplate', item)
    },
    updateComponentData(field, value) {
      let data = {
        _id: this.selectedComponent._id,
        field: field,
        value: value,
      }
      this.editComponent(data)
    }
  }
}
</script>

<style lang="less" scoped>
.image-template {
  padding: 10px;
  .template-list {
    display: flex;
    margin-top: 10px;

    .item {
      width: 50px;
      height: 50px;
      border: 1px solid #ccc;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
    }

    .item-on {
      background: rgba(59, 127, 255, 0.2);
      border: 1px solid rgba(59, 127, 255, 1);
    }
  }
}
</style>